import json
import datetime
from functools import wraps

from ..exceptions import InvalidParameterError


def strtodatetime(date_string, format='%Y-%m-%dT%H:%M:%S'):
    return datetime.datetime.strptime(date_string, format)


def strtodate(date_string, format='%Y-%m-%d'):
    return datetime.datetime.strptime(date_string, format).date()


def strtotime(date_string, format='%H:%M:%S'):
    return datetime.datetime.strptime(date_string, format).time()


class paramsValidator:
    """参数检查修饰器
    """
    def __init__(self, update=False):
        self.update = update

    def __call__(self, f):
        @wraps(f)
        def wrapper(*args, **kwargs):
            obj = args[0]  # Get object's self
            kwargs = kwargs or {}
            if not obj.validator.validate(kwargs, update=self.update):
                raise InvalidParameterError(json.dumps(obj.validator.errors))
            kwargs = obj.validator.validated(kwargs)
            return f(*args, **kwargs)
        return wrapper
